package com.krmes.mes;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.NotificationCompat.WearableExtender;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;


/**
 * Created by Administrator on 2017-02-22.
 */
public class ProcessActivity extends Activity {
    private static final int DRAG = 1;
    private static final int NONE = 0;
    private static final int ZOOM = 2;

    private ImageView imageShow;
    private Button btn_upload;
    private EditText etcomment;

    private Bitmap bmp;
    private Bitmap mbmp;
    private Bitmap alteredBitmap;

    private Canvas canvas;
    private Matrix matrix;
    private Matrix savedMatrix;
    private Paint paint;

    public String pathPicture;
    public String comment;
    private int flagOnTouch = 0;
    private PointF startPoint;
    private PointF middlePoint;
    private int mode;
    private float oldDist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_process);
        this.imageShow = (ImageView)findViewById(R.id.imageView1);
        this.btn_upload = (Button)findViewById(R.id.btn_upload);
        this.etcomment = (EditText)findViewById(R.id.et_comment);

        ShowPhotoByImageView(getIntent().getStringExtra("path"));

        this.btn_upload.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                try {
                    if (ProcessActivity.this.mbmp == null) {
                        ProcessActivity.this.mbmp = ProcessActivity.this.bmp;
                    }
                    ProcessActivity.this.comment = ProcessActivity.this.etcomment.getText().toString().trim();
                    Uri uri = Uri.fromFile(new File(ProcessActivity.this.pathPicture));// ProcessActivity.this.loadBitmap(ProcessActivity.this.mbmp);
                    Intent intent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
                    intent.setData(uri);
                    ProcessActivity.this.sendBroadcast(intent);
                    Intent intentPut = new Intent(ProcessActivity.this, MainActivity.class);
                    intentPut.putExtra("pathProcess", ProcessActivity.this.pathPicture);
                    intentPut.putExtra("comment", ProcessActivity.this.comment);
                    ProcessActivity.this.setResult(-1, intentPut);
                    ProcessActivity.this.finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        this.imageShow.setOnTouchListener(new View.OnTouchListener(){
            float downx = 0.0F;
            float downy = 0.0F;
            float upx = 0.0F;
            float upy = 0.0F;
            private float spacing(MotionEvent event) {
                float x = event.getX(ProcessActivity.NONE) - event.getX(ProcessActivity.DRAG);
                float y = event.getY(ProcessActivity.NONE) - event.getY(ProcessActivity.DRAG);
                return (float) Math.sqrt((x * x) + (y * y));
            }

            private void midPoint(PointF point, MotionEvent event) {
                point.set((event.getX(ProcessActivity.NONE) + event.getX(ProcessActivity.DRAG)) / 2.0f, (event.getY(ProcessActivity.NONE) + event.getY(ProcessActivity.DRAG)) / 2.0f);
            }

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                ImageView view = (ImageView) v;
                if (ProcessActivity.this.flagOnTouch == ProcessActivity.DRAG) {
                    switch (event.getAction() & MotionEvent.ACTION_MASK) {
                        case ProcessActivity.NONE /*0*/:
                            ProcessActivity.this.savedMatrix.set(ProcessActivity.this.matrix);
                            ProcessActivity.this.startPoint.set(event.getX(), event.getY());
                            ProcessActivity.this.mode = ProcessActivity.DRAG;
                            break;
                        case ProcessActivity.DRAG /*1*/:
//                        case FragmentManagerImpl.ANIM_STYLE_FADE_EXIT /*6*/:
//                            ProcessActivity.this.mode = ProcessActivity.NONE;
//                            break;
                        case ProcessActivity.ZOOM /*2*/:
                            if (ProcessActivity.this.mode != ProcessActivity.DRAG) {
                                if (ProcessActivity.this.mode == ProcessActivity.ZOOM) {
                                    float newDist = spacing(event);
                                    if (newDist > 10.0f) {
                                        ProcessActivity.this.matrix.set(ProcessActivity.this.savedMatrix);
                                        float scale = newDist / ProcessActivity.this.oldDist;
                                        ProcessActivity.this.matrix.postScale(scale, scale, ProcessActivity.this.middlePoint.x, ProcessActivity.this.middlePoint.y);
                                        break;
                                    }
                                }
                            }
                            ProcessActivity.this.matrix.set(ProcessActivity.this.savedMatrix);
                            ProcessActivity.this.matrix.postTranslate(event.getX() - ProcessActivity.this.startPoint.x, event.getY() - ProcessActivity.this.startPoint.y);
                            break;
                        //break;
                        case WearableExtender.SIZE_FULL_SCREEN /*5*/:
                            ProcessActivity.this.oldDist = spacing(event);
                            if (ProcessActivity.this.oldDist > 10.0f) {
                                ProcessActivity.this.savedMatrix.set(ProcessActivity.this.matrix);
                                midPoint(ProcessActivity.this.middlePoint, event);
                                ProcessActivity.this.mode = ProcessActivity.ZOOM;
                                break;
                            }
                            break;
                    }
                    view.setImageMatrix(ProcessActivity.this.matrix);
                    return true;
                } else if (ProcessActivity.this.flagOnTouch != ProcessActivity.ZOOM) {
                    return false;
                } else {
                    switch (event.getAction()) {
                        case ProcessActivity.NONE /*0*/:
                            this.downx = event.getX();
                            this.downy = event.getY();
                            break;
                        case ProcessActivity.DRAG /*1*/:
                            this.upx = event.getX();
                            this.upy = event.getY();
                            ProcessActivity.this.canvas.drawLine(this.downx, this.downy, this.upx, this.upy, ProcessActivity.this.paint);
                            ProcessActivity.this.imageShow.invalidate();
                            break;
                        case ProcessActivity.ZOOM /*2*/:
                            this.upx = event.getX();
                            this.upy = event.getY();
                            ProcessActivity.this.canvas.drawLine(this.downx, this.downy, this.upx, this.upy, ProcessActivity.this.paint);
                            ProcessActivity.this.imageShow.invalidate();
                            this.downx = this.upx;
                            this.downy = this.upy;
                            break;
                    }
                    return true;
                }

            }
        });

    }
    private void ShowPhotoByImageView(String path) {
        if (path == null) {
            Toast.makeText(this, "载入图片失败", Toast.LENGTH_SHORT).show();
            finish();
        }
        ProcessActivity.this.pathPicture = path;
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        try {
            Options bmpFactoryOptions = new Options();
            bmpFactoryOptions.inJustDecodeBounds = true;
            this.bmp = BitmapFactory.decodeFile(path, bmpFactoryOptions);
            int heightRatio = (int) Math.ceil((double) (((float) bmpFactoryOptions.outHeight) / ((float) height)));
            int widthRatio = (int) Math.ceil((double) (((float) bmpFactoryOptions.outWidth) / ((float) width)));
            if (heightRatio > DRAG && widthRatio > DRAG) {
                if (heightRatio > widthRatio) {
                    bmpFactoryOptions.inSampleSize = heightRatio * ZOOM;
                } else {
                    bmpFactoryOptions.inSampleSize = widthRatio * ZOOM;
                }
            }
            bmpFactoryOptions.inJustDecodeBounds = false;
            this.bmp = BitmapFactory.decodeFile(path, bmpFactoryOptions);
            this.mbmp = this.bmp.copy(Config.ARGB_8888, true);
            this.imageShow.setImageBitmap(this.bmp);
            this.alteredBitmap = Bitmap.createBitmap(this.bmp.getWidth(), this.bmp.getHeight(), this.bmp.getConfig());
            this.canvas = new Canvas(this.alteredBitmap);
            this.paint = new Paint();
            this.paint.setColor(Color.RED);//-16711936 ??????
            this.paint.setStrokeWidth(5.0f);
            this.paint.setTextSize(30.0f);
            this.paint.setTypeface(Typeface.DEFAULT_BOLD);
            this.matrix = new Matrix();
            this.canvas.drawBitmap(this.bmp, this.matrix, this.paint);

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
    public Uri loadBitmap(Bitmap bmp) throws IOException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        if(!path.exists()) {
            path.mkdir();
        }
        File imagePath = new File(path, filename+".jpg");
        imagePath.createNewFile();
        FileOutputStream fos = new FileOutputStream(imagePath);
        bmp.compress(Bitmap.CompressFormat.JPEG, 0x64, fos);
        fos.flush();
        fos.close();
        pathPicture = imagePath.toString();
        Uri i = Uri.fromFile(imagePath);
        return i;
    }
}
